package com.cowin.utils;

import javax.persistence.Column;
import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * Copyright (C), 1998-2018, 奇瑞信息
 *
 * @author : 于超
 * @Date: 2019/8/30 10:21
 * @Description:
 */
public class ClazzUtils {

    /**
     * 获取实体类上的 Column注解内的name值
     *
     * @param clazz 要获取的类
     * @param field 要获取的属性值
     * @return Column 的name 值  null -> ""
     */
    public static String getFieldAnnotationColumnName(Class clazz, String field) {
        Field declaredField;
        String returnAnnotationValue = "";
        try {
            declaredField = clazz.getDeclaredField(field);
            if (declaredField != null) {
                Column column = declaredField.getAnnotation(Column.class);
                if (column != null) {
                    returnAnnotationValue = column.name();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return returnAnnotationValue;
    }


    /**
     * 为指定了Id的属性动态装载guid
     *
     * @param model 需要装载的实体类
     * @param <T>   auto model
     */
    public static <T> void injectGuid(T model) {
        Field[] declaredFields = model.getClass().getDeclaredFields();
        if (declaredFields != null) {
            for (Field f : declaredFields) {
                if (f.getAnnotation(Id.class) != null&&f.getType()==String.class) {
                    Class<?> type = f.getType();
                    try {
                        f.setAccessible(true);
                        Object o = f.get(model);
                        if (o == null) {
                            f.set(model, UUIDUtils.getUUID());
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    return;
                }
            }
        }
    }

    /**
     * 自动生成时间
     *
     * @param model
     * @param <T>
     */
    public static <T> void injectDate(T model,Class autoDate) {
        Field[] declaredFields = model.getClass().getDeclaredFields();
        if (declaredFields != null) {
            for (Field f : declaredFields) {
                if (f.getAnnotation(autoDate) != null) {
                    Class<?> type = f.getType();
                    if (type.getSimpleName().equals(Date.class.getSimpleName())) {
                        try {
                            f.setAccessible(true);
                            f.set(model, new Date());
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    return;
                }
            }
        }
    }
}
